package cn.db101.gocentdaily.controller;

import cn.db101.gocentdaily.entity.SysUser;
import cn.db101.gocentdaily.model.LoginModel;
import cn.db101.gocentdaily.model.ResultModel;
import cn.db101.gocentdaily.service.SysUserService;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author zooy
 * @create 2024-06-02 2:16
 * @description
 */
@RestController
@RequestMapping("cn/db101/gocent")
public class LoginController {

    @Autowired
    private SysUserService sysUserService;

    @PostMapping("login")
    public ResultModel login(@RequestBody SysUser sysUser) {

        boolean success = sysUserService.login(sysUser.getUsername(), sysUser.getPassword());

        if (!success) {
            return ResultModel.failed("登录失败");
        }

        // 查询当前用户
        SysUser user = sysUserService.getOne(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUsername, sysUser.getUsername()));

        StpUtil.login(user.getId());

        LoginModel loginModel = new LoginModel();
        loginModel.setToken(StpUtil.getTokenValue());
        loginModel.setUserId(user.getId());
        loginModel.setUsername(user.getUsername());

        return ResultModel.success(loginModel);
    }

}
